package oct2013.linkednode;

/**
 * @author Yinzi Chen
 * @date Nov 14, 2013
 */
public class AddTwoNumbers {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode cur = dummy;
        int carry = 0;
        while (l1 != null & l2 != null) {
            int val = l1.val + l2.val + carry;
            carry = val / 10;
            val %= 10;
            cur.next = new ListNode(val);
            cur = cur.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        while (l1 != null) {
            int val = carry + l1.val;
            carry = val / 10;
            val %= 10;
            cur.next = new ListNode(val);
            cur = cur.next;
            l1 = l1.next;
        }
        while (l2 != null) {
            int val = carry + l2.val;
            carry = val / 10;
            val %= 10;
            cur.next = new ListNode(val);
            cur = cur.next;
            l2 = l2.next;
        }
        if (carry != 0) {
            cur.next = new ListNode(carry);
        }
        return dummy.next;
    }
}
